package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.dto.ShoppingCartDTO;
import com.sky.entity.Setmeal;
import com.sky.entity.ShoppingCart;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.service.ShoppingCartService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {

	@Autowired
	private ShoppingCartMapper shoppingCartMapper;

	@Autowired
	private DishMapper dishMapper;

	@Autowired
	private SetmealMapper setmealMapper;

	@Override
	public void addShoppingCart(ShoppingCartDTO shoppingCartDTO) {
		ShoppingCart shoppingCart = new ShoppingCart();
		BeanUtils.copyProperties(shoppingCartDTO, shoppingCart);
		//添加用户id
		Long userId = BaseContext.getCurrentId();
		shoppingCart.setUserId(userId);
		List<ShoppingCart> list = shoppingCartMapper.list(shoppingCart);
		if (list != null && !list.isEmpty()) {
			//购物车中已有该商品，数量加1
			ShoppingCart cart = list.get(0);
			cart.setNumber(cart.getNumber() + 1);
			shoppingCartMapper.updateNumById(cart);
		} else {
			//如果是加入的是dish
			if (shoppingCart.getDishId() != null) {
				DishVO dishVO = dishMapper.getById(shoppingCart.getDishId());
				shoppingCart.setName(dishVO.getName());
				shoppingCart.setImage(dishVO.getImage());
				shoppingCart.setAmount(dishVO.getPrice());
				//TODO 添加flavor后续完成
				//if (dishVO.getFlavors() != null) shoppingCart.setDishFlavor(dishVO.getFlavors().toString());
			} else {
				//如果是加入的是setmeal
				Setmeal setmeal = setmealMapper.getById(shoppingCart.getSetmealId());
				shoppingCart.setName(setmeal.getName());
				shoppingCart.setImage(setmeal.getImage());
				shoppingCart.setAmount(setmeal.getPrice());
			}
			shoppingCart.setNumber(1);
			shoppingCart.setCreateTime(LocalDateTime.now());
			shoppingCartMapper.insert(shoppingCart);
		}

		//shoppingCartMapper.addShoppingCart(shoppingCart);
	}

	@Override
	public List<ShoppingCart> list() {
		Long userId = BaseContext.getCurrentId();
		return shoppingCartMapper.getListByUserId(userId);
	}

	@Override
	public void remove() {
		Long userId = BaseContext.getCurrentId();
		shoppingCartMapper.remove(userId);
	}
}
